#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
**=============================================================
 * Copyright: 2012~2015 NSN
 * FullName: utils.sql_base
 * Description: 
 * Changes: 
 *==============================================================
 * Date: Apr 16, 2014
 * Author: y21chen(yong-cy.chen@nsn.com)          
 * Comment:  Create file, implement feature    
**==============================================================
"""
import re
from mysql import connector
import db_config

class GetDBConfig(object):
    def __init__(self):
        self._getConfig()
        
    def _getConfig(self):
        self.host = getattr(db_config,'DATABASE_HOST')
        self.user = getattr(db_config,'DATABASE_USER')
        self.passwd = getattr(db_config,'DATABASE_PASSWORD')
        self.db = getattr(db_config,'DATABASE_NAME')
        self.port = getattr(db_config,'DATABASE_PORT')

class GetConnection(object):
    
    def __init__(self):
        self.__initmydb()
        
    def __initmydb(self):
        config = GetDBConfig()
        mydb = connector.connect(host = config.host, user = config.user, passwd = config.passwd,
                                db = config.db, port = config.port)
        self.mydb = mydb
        self.my_cursor = self.mydb.cursor()

    def get_mydb(self):
        '''
            Get the database connection
        '''
        return self.mydb
    
    def close_mydb(self):
        '''
            Close the database connection
        '''
        self.mydb.close()
        
    def get_cursor(self):
        '''
            Get the connection cursor
        '''
        return self.my_cursor
    
    def close_cursor(self):
        '''
            Close the connection cursor
        '''
        self.my_cursor.close()
    
    def commit(self):
        '''
            Commit the connection's transaction
        '''
        self.mydb.commit()
    
    def exec_sql(self,sql):
        print(sql)
        self.get_cursor().execute(sql)
        if re.search('^\W*select',sql):
            results = self.my_cursor.fetchall()
        elif re.search('^\W*insert',sql):
            results = self.my_cursor.lastrowid
        else:
            results = self.my_cursor.rowcount
        self.commit()
        self.close_cursor()
        self.close_mydb()
        return results

    
if __name__ == '__main__':
    conn = GetConnection()

